/**
 * @program: LeetCode
 * @description: LeetCode :剑指 offer II 023. 两个链表的第一个重合节点
 * @author: WXY
 * @create: 2022-12-24 13:54
 * @Version 1.0
 **/

public class offer_serven3_getIntersectionNode {
    public static class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int n = 0;
        ListNode n1 = headA;
        ListNode n2 = headB;
        while (n1.next != null) {
            n++;
            n1 = n1.next;
        }
        while (n2.next != null) {
            n--;
            n2 = n2.next;
        }
        if (n1 != n2) return null;
        ListNode head1 = n > 0 ? headA : headB;
        ListNode head2 = head1 == headA ? headB : headA;
        n = Math.abs(n);
        while (n != 0) {
            n--;
            head1 = head1.next;
        }
        while (head2 != head1) {
            head2 = head2.next;
            head1 = head1.next;
        }
        return head1;
    }
}
